<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\PatentApply;
use App\Services\FileService;
use App\Services\JWT\JWTService;
use App\Services\PatentApplyService;

class FilePreviewController extends Controller
{
    protected $patentApplyService;
    public $fileService;

    public function __construct(FileService $fileService, PatentApplyService $patentApplyService)
    {
        $this->patentApplyService = $patentApplyService;
        $this->fileService = $fileService;
    }

    public function online($path = null)
    {
        return $this->fileService->responseStream($path, request()->get('action', 'download'), request()->get('name'));
    }

    public function preview($id, $action)
    {
        try {
            if ($token = request()->get('token')) {
                $res = JWTService::decode($token);
                if ($path = $res->$id) {
                    return $this->fileService->responseStream($path, $action, $res->name ?? '');
                }
            }
        } catch (\Exception $e) {
        }
        return response()->view('errors.404', [], 404);
    }

    public function patentApplyTable($id)
    {
        $model = PatentApply::query()->findOrFail($id);
        if ($model instanceof PatentApply && $model->checkToken()) {
            return $this->patentApplyService->downloadTable($model);
        }
        return response()->view('errors.404');
    }

}
